import { setToken, removeToken } from '../../utils/auth'
import { setStore, getStore } from '../../utils/store'
import { encryption, deepClone } from '../../utils/util'
import { userMenu, top } from '../../utils/menu'
import { getUserInfo, logout, refeshToken } from '../../api/user'
import { formatPath } from '../../router/avue-router'
import {ElMessage} from 'element-plus';
import {LoginByPhoneApi, loginByUsername} from '../../api/login';

const user = {
  state: {
    userId: getStore({name: 'userId'})||'',
    userInfo: {},
    permission: {},
    roles: [],
    menuId: {},
    menu: getStore({ name: 'menu' }) || [],
    menuAll: getStore({ name: 'menuAll' }) || [],
    token: getStore({ name: 'token' }) || '',
  },
  actions: {
    //根据用户名登录
    LoginByUsername ({ commit }, userInfo = {}) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.userId, userInfo.password).then(res => {
          const data = res.data.result;
          if(data === "noExist"){
            ElMessage.error("该账号不存在，请注册！")
            return;
          }else if(res.data.errorMsg === "databaseError"){
            ElMessage.error("数据库错误，请重试！")
            return;
          }else if(data === "error"){
            ElMessage.error("账号密码错误，请重试！")
            return;
          } else {
            commit('SET_TOKEN', data);
            commit('SET_USERID',userInfo.userId);
            commit('DEL_ALL_TAG', []);
            commit('CLEAR_LOCK');
            resolve();
          }
        })
      })
    },
    //根据手机号登录
    LoginByPhone ({ commit }, userInfo) {
      return new Promise((resolve) => {
        LoginByPhoneApi(userInfo.userId, userInfo.checkCode).then(res => {
          const data = res.data.result;
          if(data === "noExist"){
            ElMessage.error("该账号不存在，请注册！")
            return;
          }else if(res.data.errorMsg === "databaseError"){
            ElMessage.error("数据库错误，请重试！")
            return;
          }else if(data === "codeError"){
            ElMessage.error("验证码错误，请重新获取！")
            return;
          }else if(data === "timeOut"){
            ElMessage.error("验证码已过期，请重新获取！")
            return;
          } else {
            commit('SET_TOKEN', data);
            commit('SET_USERID',userInfo.userId);
            commit('DEL_ALL_TAG', []);
            commit('CLEAR_LOCK');
            resolve();
          }

        })
      })
    },
    GetUserInfo ({ commit },userId) {
      return new Promise((resolve, reject) => {
        getUserInfo(userId).then((res) => {
          const data = res.data.result;
          if(res.data.errorMsg === "no"){
            ElMessage.error("获取用户信息失败，请重试！")
            reject(res.data.errorMsg)
          }else {
            const userInfo = {
              username: data.userName,
              avatar: data.userAvatar,
              status: data.userStatus
            }
            commit('SET_USERIFNO', userInfo);
            commit('SET_ROLES', data.userRole);
            resolve(data);
          }
        }).catch(err => {
          reject(err);
        })
      })
    },
    //刷新token
    RefeshToken ({ state, commit }) {
      return new Promise((resolve, reject) => {
        refeshToken(state.refeshToken).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN', data);
          resolve(data);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_MENUALL_NULL', []);
          commit('SET_MENU', [])
          commit('SET_ROLES', [])
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    //注销session
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_MENUALL_NULL', []);
        commit('SET_MENU', [])
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG', []);
        commit('CLEAR_LOCK');
        removeToken()
        resolve()
      })
    },
    GetTopMenu () {
      return new Promise(resolve => {
          const data = top || []
          resolve(data)

      })
    },
    //获取系统菜单
    GetMenu ({ commit }, parentId) {
      return new Promise(resolve => {
          const data = userMenu[0]
          let menu = deepClone(data);
          menu.forEach(ele => formatPath(ele, true));
          commit('SET_MENUALL', menu)
          commit('SET_MENU', menu)
          resolve(menu)
      })
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      setToken(token)
      state.token = token;
      setStore({ name: 'token', content: state.token })
    },
    SET_MENUID (state, menuId) {
      state.menuId = menuId;
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
      setStore({name: 'userId', content: state.userId})
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_MENUALL: (state, menuAll) => {
      let menu = state.menuAll;
      menuAll.forEach(ele => {
        let index = menu.findIndex(item => item.path == ele.path)
        if (index == -1) {
          menu.push(ele);
        } else {
          menu[index] = ele;
        }
      })
      state.menuAll = menu
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENUALL_NULL: (state) => {
      state.menuAll = []
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({ name: 'menu', content: state.menu })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = {};
      permission.forEach(ele => {
        state.permission[ele] = true;
      });
    }
  }

}
export default user
